package com.itheima.controller.backend.security;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    /**
     * 查询
     */
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Pageable pageable = PageRequest.of(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (queryString != null && !queryString.isEmpty()) {
            // 判断是否为 code 查询（可自定义逻辑）
            if (isCodeQuery(queryString)) {
                return orderService.findPageByCode(pageable, queryString);
            } else {
                return orderService.findPageByName(pageable, queryString);
            }
        }
        // 当 queryString 为空时，调用默认分页查询方法
        else {
            return findPageDefault(pageable);
        }
    }
    private boolean isCodeQuery(String keyword) {
        // 可以根据业务逻辑判断是否是 code 查询，例如只包含字母数字时认为是 code
        return keyword.matches("[a-zA-Z0-9]+");
    }

    private PageResult findPageDefault(Pageable pageable) {
        return orderService.findPageDefault(pageable);
    }

    @PostMapping("/findPageByCode")
    public PageResult findPageByCode(@RequestBody QueryPageBean queryPageBean) {
        Pageable pageable = PageRequest.of(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        return orderService.findPageByCode(pageable, queryPageBean.getQueryString());
    }
    @PostMapping("/findPageByName")
    public PageResult findPageByName(@RequestBody QueryPageBean queryPageBean) {
        Pageable pageable = PageRequest.of(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        return orderService.findPageByName(pageable, queryPageBean.getQueryString());
    }
    /**
     * 修改状态
     */
    @PostMapping("/update")
    public boolean update(@RequestBody Order order) {
        return orderService.update(order);
    }
    /**
     * id查询
     */
    @GetMapping("/findById")
    public Order findById(@RequestParam Integer id) {
        return orderService.findById(id);
    }


}

